﻿// The MIT License (MIT)
// Copyright (c) 2014 Grégory Ghez
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

namespace Jenkins.Core.Tests
{
    using System;
    using System.Linq;
    using System.Threading.Tasks;
    using Domain;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using Moq;
    using Ploeh.AutoFixture;

    [TestClass]
    public class JenkinsRestClientTests
    {
        private readonly Fixture defaultFixture = new Fixture();
        private JenkinsRestClient defaultClient;
        private Mock<IRestManager> restManager;

        [TestInitialize]
        public void InitContext()
        {
            this.restManager = new Mock<IRestManager>();
            this.defaultClient = new JenkinsRestClient(this.restManager.Object);
        }

        [TestMethod]
        [ExpectedException(typeof(ArgumentNullException))]
        public void Invoke_Constructor_WithNullRestManager_ShouldFailed()
        {
            new JenkinsRestClient(null);
        }

        [TestMethod]
        public void Invoke_GetServerAsync_WithNullUrl_ShouldFailed()
        {
            try
            {
                this.defaultClient.GetServerAsync(null);
            }
            catch (AggregateException aggEx)
            {
                Assert.IsTrue(aggEx.InnerException is ArgumentNullException);
            }
        }

        [TestMethod]
        public void Invoke_GetJobAsync_WithNullUrl_ShouldFailed()
        {
            try
            {
                this.defaultClient.GetJobAsync(null).Wait();
            }
            catch (AggregateException aggEx)
            {
                Assert.IsTrue(aggEx.InnerException is ArgumentNullException);
            }
        }

        [TestMethod]
        public void Invoke_GetViewAsync_WithNullUrl_ShouldFailed()
        {
            try
            {
                this.defaultClient.GetViewAsync(null).Wait();
            }
            catch (AggregateException aggEx)
            {
                Assert.IsTrue(aggEx.InnerException is ArgumentNullException);
            }
        }

        [TestMethod]
        public void Invoke_GetBuildAsync_WithNullUrl_ShouldFailed()
        {
            try
            {
                this.defaultClient.GetBuildAsync(null).Wait();
            }
            catch (AggregateException aggEx)
            {
                Assert.IsTrue(aggEx.InnerException is ArgumentNullException);
            }
        }

        [TestMethod]
        public void Invoke_RunJobAsync_WithNullJob_ShouldFailed()
        {
            try
            {
                this.defaultClient.RunJobAsync(null).Wait();
            }
            catch (AggregateException aggEx)
            {
                Assert.IsTrue(aggEx.InnerException is ArgumentNullException);
            }
        }

        [TestMethod]
        public void Invoke_StopJobAsync_WithNullJob_ShouldFailed()
        {
            try
            {
                this.defaultClient.StopJobAsync(null).Wait();
            }
            catch (AggregateException aggEx)
            {
                Assert.IsTrue(aggEx.InnerException is ArgumentNullException);
            }
        }

        [TestMethod]
        public void Invoke_GetServerAsync_ShouldCall_LoadAsync()
        {
            var url = this.defaultFixture.Create<string>();
            this.defaultClient.GetServerAsync(url).Wait();

            this.restManager.Verify(m => m.LoadAsync<JenkinsServer>(It.IsAny<string>()), Times.Once);
            this.restManager.Verify(m => m.LoadAsync<JenkinsNode>(It.IsAny<string>()), Times.Once);
        }

        /// <summary>
        /// TODO: Use a caching system to avoid multiple job/build REST request.
        /// </summary>
        [TestMethod]
        [Ignore]
        public void Invoke_GetServerAsync_WithDepthLoad_ShouldCall_LoadAsync()
        {
            var node = this.defaultFixture.Create<JenkinsNode>();

            // Avoid invalid node state
            foreach (JenkinsView view in node.Views)
            {
                view.Jobs = node.Jobs.ToArray();
            }

            // Primary view must be in Views array
            node.PrimaryView = node.Views.First();

            // Directly referenced jobs must be in Builds array
            foreach (var job in node.Jobs)
            {
                job.LastBuild = job.Builds.First();
                job.LastCompletedBuild = job.Builds.First();
                job.LastFailedBuild = job.Builds.First();
                job.LastStableBuild = job.Builds.First();
                job.LastSuccessfulBuild = job.Builds.First();
                job.LastUnstableBuild = job.Builds.First();
                job.LastUnsuccessfulBuild = job.Builds.First();
            }

            var url = this.defaultFixture.Create<string>();

            this.restManager.Setup(m => m.LoadAsync<JenkinsNode>(It.IsAny<string>()))
                .Returns(() =>
                {
                    var tcs = new TaskCompletionSource<JenkinsNode>();
                    tcs.SetResult(node);
                    return tcs.Task;
                });

            this.restManager.Setup(m => m.LoadAsync<JenkinsJob>(It.IsAny<string>()))
                .Returns((string jobUrl) =>
                {
                    var tcs = new TaskCompletionSource<JenkinsJob>();
                    tcs.SetResult(node.Jobs.First(j => string.Equals(j.RestUrl, jobUrl, StringComparison.OrdinalIgnoreCase)));
                    return tcs.Task;
                });

            this.restManager.Setup(m => m.LoadAsync<JenkinsView>(It.IsAny<string>()))
                .Returns((string viewUrl) =>
                {
                    var tcs = new TaskCompletionSource<JenkinsView>();
                    tcs.SetResult(node.Views.First(v => string.Equals(v.DetailsUrl, viewUrl, StringComparison.OrdinalIgnoreCase)));
                    return tcs.Task;
                });

            this.restManager.Setup(m => m.LoadAsync<JenkinsBuild>(It.IsAny<string>()))
                .Returns((string buildUrl) =>
                {
                    var tcs = new TaskCompletionSource<JenkinsBuild>();
                    tcs.SetResult(node.Jobs.SelectMany(j => j.Builds).First(b => string.Equals(b.RestUrl, buildUrl, StringComparison.OrdinalIgnoreCase)));
                    return tcs.Task;
                });

            this.defaultClient.GetServerAsync(url, true).Wait();

            this.restManager.Verify(m => m.LoadAsync<JenkinsServer>(It.IsAny<string>()), Times.Once);
            this.restManager.Verify(m => m.LoadAsync<JenkinsNode>(It.IsAny<string>()), Times.Once);

            // JOBS
            foreach (JenkinsJob job in node.Jobs)
            {
                this.restManager.Verify(m => m.LoadAsync<JenkinsJob>(It.Is<string>(u => string.Equals(u, job.RestUrl, StringComparison.OrdinalIgnoreCase))), Times.Once);

                foreach (JenkinsBuild build in job.Builds)
                {
                    this.restManager.Verify(m => m.LoadAsync<JenkinsBuild>(It.Is<string>(u => string.Equals(u, build.RestUrl, StringComparison.OrdinalIgnoreCase))), Times.Once);
                }

                this.restManager.Verify(m => m.LoadAsync<JenkinsBuild>(It.Is<string>(u => string.Equals(u, job.LastBuild.RestUrl, StringComparison.OrdinalIgnoreCase))), Times.Once);
                this.restManager.Verify(m => m.LoadAsync<JenkinsBuild>(It.Is<string>(u => string.Equals(u, job.LastCompletedBuild.RestUrl, StringComparison.OrdinalIgnoreCase))), Times.Once);
                this.restManager.Verify(m => m.LoadAsync<JenkinsBuild>(It.Is<string>(u => string.Equals(u, job.LastFailedBuild.RestUrl, StringComparison.OrdinalIgnoreCase))), Times.Once);
                this.restManager.Verify(m => m.LoadAsync<JenkinsBuild>(It.Is<string>(u => string.Equals(u, job.LastStableBuild.RestUrl, StringComparison.OrdinalIgnoreCase))), Times.Once);
                this.restManager.Verify(m => m.LoadAsync<JenkinsBuild>(It.Is<string>(u => string.Equals(u, job.LastSuccessfulBuild.RestUrl, StringComparison.OrdinalIgnoreCase))), Times.Once);
                this.restManager.Verify(m => m.LoadAsync<JenkinsBuild>(It.Is<string>(u => string.Equals(u, job.LastUnstableBuild.RestUrl, StringComparison.OrdinalIgnoreCase))), Times.Once);
                this.restManager.Verify(m => m.LoadAsync<JenkinsBuild>(It.Is<string>(u => string.Equals(u, job.LastUnsuccessfulBuild.RestUrl, StringComparison.OrdinalIgnoreCase))), Times.Once);
            }

            // VIEWS
            foreach (JenkinsView view in node.Views)
            {
                this.restManager.Verify(m => m.LoadAsync<JenkinsView>(It.Is<string>(u => string.Equals(u, view.DetailsUrl, StringComparison.OrdinalIgnoreCase))), Times.Once);

                foreach (JenkinsJob job in view.Jobs)
                {
                    this.restManager.Verify(m => m.LoadAsync<JenkinsJob>(It.Is<string>(u => string.Equals(u, job.RestUrl, StringComparison.OrdinalIgnoreCase))), Times.Once);

                    foreach (JenkinsBuild build in job.Builds)
                    {
                        this.restManager.Verify(m => m.LoadAsync<JenkinsBuild>(It.Is<string>(u => string.Equals(u, build.RestUrl, StringComparison.OrdinalIgnoreCase))), Times.Once);
                    }

                    this.restManager.Verify(m => m.LoadAsync<JenkinsBuild>(It.Is<string>(u => string.Equals(u, job.LastBuild.RestUrl, StringComparison.OrdinalIgnoreCase))), Times.Once);
                    this.restManager.Verify(m => m.LoadAsync<JenkinsBuild>(It.Is<string>(u => string.Equals(u, job.LastCompletedBuild.RestUrl, StringComparison.OrdinalIgnoreCase))), Times.Once);
                    this.restManager.Verify(m => m.LoadAsync<JenkinsBuild>(It.Is<string>(u => string.Equals(u, job.LastFailedBuild.RestUrl, StringComparison.OrdinalIgnoreCase))), Times.Once);
                    this.restManager.Verify(m => m.LoadAsync<JenkinsBuild>(It.Is<string>(u => string.Equals(u, job.LastStableBuild.RestUrl, StringComparison.OrdinalIgnoreCase))), Times.Once);
                    this.restManager.Verify(m => m.LoadAsync<JenkinsBuild>(It.Is<string>(u => string.Equals(u, job.LastSuccessfulBuild.RestUrl, StringComparison.OrdinalIgnoreCase))), Times.Once);
                    this.restManager.Verify(m => m.LoadAsync<JenkinsBuild>(It.Is<string>(u => string.Equals(u, job.LastUnstableBuild.RestUrl, StringComparison.OrdinalIgnoreCase))), Times.Once);
                    this.restManager.Verify(m => m.LoadAsync<JenkinsBuild>(It.Is<string>(u => string.Equals(u, job.LastUnsuccessfulBuild.RestUrl, StringComparison.OrdinalIgnoreCase))), Times.Once);
                }
            }

            // PRIMARY VIEW
            this.restManager.Verify(m => m.LoadAsync<JenkinsView>(It.Is<string>(u => string.Equals(u, node.PrimaryView.DetailsUrl, StringComparison.OrdinalIgnoreCase))), Times.Once);

            foreach (JenkinsJob job in node.PrimaryView.Jobs)
            {
                this.restManager.Verify(m => m.LoadAsync<JenkinsJob>(It.Is<string>(u => string.Equals(u, job.RestUrl, StringComparison.OrdinalIgnoreCase))), Times.Once);

                foreach (JenkinsBuild build in job.Builds)
                {
                    this.restManager.Verify(m => m.LoadAsync<JenkinsBuild>(It.Is<string>(u => string.Equals(u, build.RestUrl, StringComparison.OrdinalIgnoreCase))), Times.Once);
                }

                this.restManager.Verify(m => m.LoadAsync<JenkinsBuild>(It.Is<string>(u => string.Equals(u, job.LastBuild.RestUrl, StringComparison.OrdinalIgnoreCase))), Times.Once);
                this.restManager.Verify(m => m.LoadAsync<JenkinsBuild>(It.Is<string>(u => string.Equals(u, job.LastCompletedBuild.RestUrl, StringComparison.OrdinalIgnoreCase))), Times.Once);
                this.restManager.Verify(m => m.LoadAsync<JenkinsBuild>(It.Is<string>(u => string.Equals(u, job.LastFailedBuild.RestUrl, StringComparison.OrdinalIgnoreCase))), Times.Once);
                this.restManager.Verify(m => m.LoadAsync<JenkinsBuild>(It.Is<string>(u => string.Equals(u, job.LastStableBuild.RestUrl, StringComparison.OrdinalIgnoreCase))), Times.Once);
                this.restManager.Verify(m => m.LoadAsync<JenkinsBuild>(It.Is<string>(u => string.Equals(u, job.LastSuccessfulBuild.RestUrl, StringComparison.OrdinalIgnoreCase))), Times.Once);
                this.restManager.Verify(m => m.LoadAsync<JenkinsBuild>(It.Is<string>(u => string.Equals(u, job.LastUnstableBuild.RestUrl, StringComparison.OrdinalIgnoreCase))), Times.Once);
                this.restManager.Verify(m => m.LoadAsync<JenkinsBuild>(It.Is<string>(u => string.Equals(u, job.LastUnsuccessfulBuild.RestUrl, StringComparison.OrdinalIgnoreCase))), Times.Once);
            }
        }

        [TestMethod]
        public void Invoke_GetJobAsync_WithNoDepthLoad_ShouldCall_LoadAsync()
        {
            var url = this.defaultFixture.Create<string>();
            this.defaultClient.GetJobAsync(url, false).Wait();

            this.restManager.Verify(m => m.LoadAsync<JenkinsJob>(It.Is<string>(u => string.Equals(u, url, StringComparison.OrdinalIgnoreCase))), Times.Once);
        }

        [TestMethod]
        public void Invoke_GetJobAsync_WithDepthLoad_ShouldCall_LoadAsync()
        {
            var url = this.defaultFixture.Create<string>();
            var builds = defaultFixture.Create<JenkinsBuild[]>();
            var job = defaultFixture.Create<JenkinsJob>();
            job.Builds = builds;
            job.LastBuild = builds[0];
            job.FirstBuild = builds[0];
            job.LastCompletedBuild = builds[1];
            job.LastFailedBuild = builds[2];
            job.LastStableBuild = builds[1];
            job.LastSuccessfulBuild = builds[1];
            job.LastUnstableBuild = builds[0];
            job.LastUnsuccessfulBuild = builds[1];

            restManager.Setup(m => m.LoadAsync<JenkinsJob>(It.IsAny<string>()))
                       .Returns((string jobRestUrl) =>
                       {
                           var tcs = new TaskCompletionSource<JenkinsJob>();
                           tcs.SetResult(job);
                           return tcs.Task;
                       });

            restManager.Setup(m => m.LoadAsync<JenkinsBuild>(It.IsAny<string>()))
                       .Returns((string buildRestUrl) =>
                       {
                           var tcs = new TaskCompletionSource<JenkinsBuild>();
                           tcs.SetResult(builds.First(b => string.Equals(b.RestUrl, buildRestUrl, StringComparison.OrdinalIgnoreCase)));
                           return tcs.Task;
                       });

            this.defaultClient.GetJobAsync(url, true).Wait();

            this.restManager.Verify(m => m.LoadAsync<JenkinsJob>(It.Is<string>(u => string.Equals(u, url, StringComparison.OrdinalIgnoreCase))), Times.Once);
            foreach (var build in builds)
            {
                restManager.Verify(m => m.LoadAsync<JenkinsBuild>(It.Is<string>(u => string.Equals(u, build.RestUrl, StringComparison.OrdinalIgnoreCase))), Times.Once);
            }
        }

        [TestMethod]
        public void Invoke_GetBuildAsync_WithNoDepthLoad_ShouldCall_LoadAsync()
        {
            var url = this.defaultFixture.Create<string>();
            this.defaultClient.GetBuildAsync(url, false).Wait();

            this.restManager.Verify(m => m.LoadAsync<JenkinsBuild>(It.Is<string>(u => string.Equals(u, url, StringComparison.OrdinalIgnoreCase))), Times.Once);
        }

        [TestMethod]
        public void Invoke_GetBuildAsync_WithDepthLoad_ShouldCall_LoadAsync()
        {
            var url = this.defaultFixture.Create<string>();

            restManager.Setup(m => m.LoadAsync<JenkinsBuild>(It.IsAny<string>())).Returns(() =>
            {
                var tcs = new TaskCompletionSource<JenkinsBuild>();
                tcs.SetResult(new JenkinsBuild
                              {
                                  Url = url
                              });
                return tcs.Task;
            });

            this.defaultClient.GetBuildAsync(url, true).Wait();

            this.restManager.Verify(m => m.LoadAsync<JenkinsBuild>(It.Is<string>(u => string.Equals(u, url, StringComparison.OrdinalIgnoreCase))), Times.Once);
            this.restManager.Verify(m => m.LoadAsync<JenkinsTestReport>(It.Is<string>(u => string.Equals(u, url+"testReport/api/json", StringComparison.OrdinalIgnoreCase))), Times.Once);
        }

        [TestMethod]
        public void Invoke_GetViewAsync_WithNoDepthLoad_ShouldCall_LoadAsync()
        {
            var url = this.defaultFixture.Create<string>();
            this.defaultClient.GetViewAsync(url, false).Wait();

            this.restManager.Verify(m => m.LoadAsync<JenkinsView>(It.Is<string>(u => string.Equals(u, url, StringComparison.OrdinalIgnoreCase))), Times.Once);
        }

        [TestMethod]
        public void Invoke_GetViewAsync_WithDepthLoad_ShouldCall_LoadAsync()
        {
            var url = this.defaultFixture.Create<string>();
            var jobs = defaultFixture.Create<JenkinsJob[]>();
            var view = defaultFixture.Create<JenkinsView>();
            view.Url = url;
            view.Jobs = jobs;

            restManager.Setup(m => m.LoadAsync<JenkinsView>(It.IsAny<string>()))
                       .Returns(() =>
                       {
                           var tcs = new TaskCompletionSource<JenkinsView>();
                           tcs.SetResult(view);
                           return tcs.Task;
                       });

            restManager.Setup(m => m.LoadAsync<JenkinsJob>(It.IsAny<string>()))
                       .Returns((string jobRestUrl) =>
                       {
                           var tcs = new TaskCompletionSource<JenkinsJob>();
                           tcs.SetResult(jobs.First(j=>string.Equals(j.RestUrl, jobRestUrl, StringComparison.OrdinalIgnoreCase)));
                           return tcs.Task;
                       });

            restManager.Setup(m => m.LoadAsync<JenkinsBuild>(It.IsAny<string>()))
                      .Returns((string buildRestUrl) =>
                      {
                          var tcs = new TaskCompletionSource<JenkinsBuild>();
                          tcs.SetResult(defaultFixture.Create<JenkinsBuild>());
                          return tcs.Task;
                      });

            this.defaultClient.GetViewAsync(url, true).Wait();

            this.restManager.Verify(m => m.LoadAsync<JenkinsView>(It.Is<string>(u => string.Equals(u, url, StringComparison.OrdinalIgnoreCase))), Times.Once);
            foreach (var job in view.Jobs)
            {
                restManager.Verify(m => m.LoadAsync<JenkinsJob>(It.Is<string>(u => string.Equals(u, job.RestUrl, StringComparison.OrdinalIgnoreCase))), Times.Once);
            }
        }

        [TestMethod]
        public void Invoke_GetTestReportAsync_ShouldCall_LoadAsync()
        {
            var url = this.defaultFixture.Create<string>();
            this.defaultClient.GetTestReportAsync(url).Wait();

            this.restManager.Verify(m => m.LoadAsync<JenkinsTestReport>(It.Is<string>(u => string.Equals(u, url, StringComparison.OrdinalIgnoreCase))));
        }

        [TestMethod]
        public void Invoke_RunJobAsync_ShouldCall_PostDataAsync()
        {
            var job = this.defaultFixture.Create<JenkinsJob>();
            this.defaultClient.RunJobAsync(job).Wait();

            this.restManager.Verify(m => m.PostDataAsync(It.Is<string>(u => string.Equals(u, job.BuildRestUrl, StringComparison.OrdinalIgnoreCase)), It.Is<string>(d => string.Equals(d, string.Empty))), Times.Once);
        }

        [TestMethod]
        public void Invoke_StopJobAsync_ShouldCall_PostDataAsync()
        {
            var job = this.defaultFixture.Create<JenkinsJob>();
            this.defaultClient.StopJobAsync(job).Wait();

            this.restManager.Verify(m => m.PostDataAsync(It.Is<string>(u => string.Equals(u, job.LastBuild.StopRestUrl, StringComparison.OrdinalIgnoreCase)), It.Is<string>(d => string.Equals(d, string.Empty))), Times.Once);
        }

        [TestMethod]
        public void Invoke_StopJobAsync_WithNullLastBuild_ShouldNotCall_PostDataAsync()
        {
            var job = this.defaultFixture.Create<JenkinsJob>();
            job.LastBuild = null;

            this.defaultClient.StopJobAsync(job).Wait();

            this.restManager.Verify(m => m.PostDataAsync(It.IsAny<string>(), It.IsAny<string>()), Times.Never);
        }

        
    }
}